# -*- coding:utf-8 -*-
"""
@author: 
@file: task.py
@time: 2023/12/14 14:16
@desc: 任务管理
"""
from django.shortcuts import render, HttpResponse
from django.views.decorators.csrf import csrf_exempt
import json
from app01.utils.bootstrap import BootStrapModelForm
from app01 import models
from django import forms
from app01.utils.pagination import Pagination


class TaskModelForm(BootStrapModelForm):
    class Meta:
        model = models.Task
        fields = "__all__"
        widgets = {
            "detail": forms.TextInput
        }


def task_list(request):
    """ 任务列表 """
    queryset = models.Task.objects.all().order_by('-id')
    page_object = Pagination(request, queryset, page_size=5)
    form = TaskModelForm()
    conten ={
        "form": form,
        "queryset": page_object.page_queryset,
        "page_string": page_object.html()
    }
    return render(request, 'task_list.html', conten)


@csrf_exempt
def task_ajax(request):

    data_dict = {"status": True, 'data': request.POST}
    json_string = json.dumps(data_dict)

    return HttpResponse(json_string)


@csrf_exempt
def task_add(request):
    """ 添加任务 """
    # 1.用户发送过来的数据进行校验(ModelForm进行验证)
    form = TaskModelForm(data=request.POST)
    if form.is_valid():
        form.save()
        data_dict = {"status": True}
        return HttpResponse(json.dumps(data_dict))

    data_dict = {"status": False, 'error': form.errors}
    return HttpResponse(json.dumps(data_dict, ensure_ascii=False))